﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Threading;
using MaxAlarm.Common.Data;
using MaxAlarm.Windows;

namespace MaxAlarm.Alerts
{
    public class AlertsManager
    {
        #region Singletone

        private static readonly object _locker = new object();
        private static AlertsManager _instance;

        public static AlertsManager Instance
        {
            get
            {
                lock (_locker)
                {
                    return _instance ?? (_instance = new AlertsManager());
                }
            }
        }

        #endregion

        private AlarmWindow _alarmWindow;
        private readonly ObservableCollection<AlarmItem> QueuedAlarms = new ObservableCollection<AlarmItem>();
        private bool _isCollectorStarted;

        private AlertsManager()
        {
        }

        public void QueueItem(AlarmItem item)
        {
            QueuedAlarms.Add(item);

            if (_isCollectorStarted)
                return;

            var worker = new BackgroundWorker {WorkerSupportsCancellation = true};
            worker.DoWork += DoWork;
            worker.RunWorkerCompleted += RunningCompleted;
        }

        private void RunningCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (_alarmWindow == null || !_alarmWindow.IsLoaded)
            {
                _alarmWindow = new AlarmWindow();
                _alarmWindow.Show();
            }

            AddToCollection(_alarmWindow.AlarmItems, QueuedAlarms);
            _isCollectorStarted = false;
            QueuedAlarms.Clear();
        }

        private static void DoWork(object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(5000);
        }

        private static void AddToCollection(ICollection<AlarmItem> target, IEnumerable<AlarmItem> source)
        {
            foreach(var item in source)
                target.Add(item);
        }
    }
}
